import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['Source Han Serif SC']
plt.rcParams['axes.unicode_minus'] = False
# 构造中性资产的超额收益纯教学示例,不代表真实证券
np.random.seed(42)
n_obs = 60
market_return = np.random.normal(0.0008, 0.015, n_obs)
risk_free_return = 0.0001 # 设置教学示例的同期无风险收益
market_excess = market_return - risk_free_return # 计算市场超额收益
beta = 1.2
alpha = 0.0002
stock_excess = alpha + beta * market_excess + np.random.normal(0, 0.01, n_obs) # 生成中性资产超额收益
# 绘制证券特征线
plt.figure(figsize=(8, 3.2)) # 使用投影安全画布为CAPM方法边界图注和页脚保留空间
plt.scatter(market_excess, stock_excess, # 绘制超额收益时间序列散点
s=80, alpha=0.6, color='#2E86AB', edgecolors='white')
# 添加拟合线
z = np.polyfit(market_excess, stock_excess, 1) # 拟合证券特征线斜率与截距
p = np.poly1d(z)
x_line = np.linspace(market_excess.min(), market_excess.max(), 100) # 生成特征线横轴网格
plt.plot(x_line, p(x_line), 'r-', linewidth=2.5, label='证券特征线(时间序列)') # 绘制拟合证券特征线
# 添加理论线(alpha=0)
plt.plot(x_line, beta * x_line, 'g--', linewidth=2, alpha=0.7, label='理论线(α=0)') # 绘制零截距对照线
plt.xlabel('市场超额收益率 $R_m-R_f$', fontsize=16) # 标注市场超额收益横轴
plt.ylabel('资产超额收益率 $R_i-R_f$', fontsize=16) # 标注资产超额收益纵轴
plt.title(f'教学示例,非市场观测|CAPM: β={beta:.2f}, α={alpha:.4f}', fontsize=16, fontweight='bold') # 在可见标题声明依据边界
plt.legend(fontsize=14, title='教学示例,非市场观测', loc='upper left') # 用紧凑图例减少对点云遮挡
plt.grid(True, alpha=0.3)
plt.axhline(y=0, color='k', linestyle='-', linewidth=0.5)
plt.axvline(x=0, color='k', linestyle='-', linewidth=0.5)
plt.tight_layout()
plt.show()